package com.o2opay.car.common.socket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * nio通讯模版
 * Created by tugou on 2017/12/29.
 */
public abstract class SocketApiTemplate {

    private static final Logger logger = LoggerFactory.getLogger(SocketApiTemplate.class);


    /**
     * socket服务端口
     */
    protected int port;

    /**
     * 服务名称
     */
    protected String name;

    protected abstract void init();

    public void run(SocketHandle handle) throws Exception {
        init();
        logger.info("【"+this.name+"服务开始启动，使用端口："+this.port+"】");
        //EventLoopGroup是用来处理IO操作的多线程事件循环器
        //bossGroup 用来接收进来的连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //workerGroup 用来处理已经被接收的连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(handle);
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128);
            ChannelFuture future = b.bind(port).sync();
            future.channel().closeFuture().sync();
        }
        finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
            logger.info("【"+this.name+"服务释放，使用端口："+this.port+"】");
        }
    }
}
